package com.tro.common.util.office;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class DocXToHtml {
	/**
	 * 
	 * @Title: docxToHtml
	 * @Description: TODO(docx 转换成 html 目前转换的html 貌似表格没有边框，，，)
	 * @param @param
	 *            fileName
	 * @param @param
	 *            path
	 * @param @param
	 *            imgPath
	 * @param @return
	 *            设定文件
	 * @return String 返回类型
	 * @throws @author
	 *             leeko
	 */
	public static String docxToHtml(String fileName, String path, String imgPath) {
		try {
			// 1) 加载word文档生成 XWPFDocument对象
			InputStream in = new FileInputStream(path + fileName);
			XWPFDocument document = new XWPFDocument(in);
            File imageFolderFile = new File(imgPath);  
            XHTMLOptions options = XHTMLOptions.create().URIResolver(  
                    new FileURIResolver(imageFolderFile));  
            options.setExtractor(new FileImageExtractor(imageFolderFile));  

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			XHTMLConverter.getInstance().convert(document, out, options);
			String content = out.toString();
			out.close();
			return content;
		} catch (Exception ex) {
			// 转换异常，不管了。。。
			ex.printStackTrace();
		}
		return "暂时不支持该文档转换....";
	}

	public static void main(String[] args) throws Throwable {
		
		final String path = "/Users/apple/Desktop/";
		final String file = "可视化系统部署文档.docx";
		String content = docxToHtml(file, path, "/Users/apple/Desktop/image/");
		FileUtils.writeStringToFile(new File(path, "test.html"), content, "utf-8");
	}

}
